// $Id: video_upload_browser.js,v 1.5.6.10 2010/06/11 18:05:51 bojanz Exp $
/**
 * JS functionality for the Video Upload Browser method.
 */

/**
 * Implementation of the "Remove" button.
 */
Drupal.behaviors.videoUploadAttachDelete = function(context) {
  $('.video-upload-browser-delete', context).click(function() {
    var elementId = this.id;
    elementId = elementId.replace('-video-browser-delete', '');

    // Remove the video thumb and status text, reset the hidden fields.
    $('#' + elementId + '-browser-item').remove();
    $('#' + elementId + '-video-status').attr('value', 'upload-pending');
    $('#' + elementId + '-video-id').attr('value', '');

    var elementWrapper = $('#' + elementId + '-wrapper');
    var buttonValue = Drupal.t('Launch the Uploader');
    var uploadButton = '<input type="submit" class="form-submit video-upload-browser-upload" value="' + buttonValue + '" id="' + elementId + '-video-browser-upload" name="op">';

    if ($('label', elementWrapper).length > 0) { // case when number of values in field is 1
      $('label', elementWrapper).after(uploadButton);
    } else { // case when number of values is more than 1
      elementWrapper.prepend(uploadButton);
    }

    // Reattach the JS callback
    Drupal.behaviors.videoUploadAttachUploaderButton(elementWrapper);

    return false;
  });
}

/**
 * Implementation of the "Launch the Uploader" button
 *  (unhides the button on page load and launches the upload dialog when clicked)
 */
Drupal.behaviors.videoUploadAttachUploaderButton = function(context) {
  $('.video-upload-browser-upload', context).show();

  $('.video-upload-browser-upload', context).click(function() {
    var elementId = this.id;
    elementId = elementId.replace('-video-browser-upload', '');
    var dialogId = 'dialog-' + elementId;
    Drupal.videoUpload.fields.push(elementId);

    var fieldName = Drupal.settings['videoUpload-' + elementId].fieldName;
    var typeName = Drupal.settings['videoUpload-' + elementId].typeName;
    var nid = Drupal.settings['videoUpload-' + elementId].nid;

    // insert the dialog div with the Loading... text into the DOM
    $('body').prepend('<div id="' + dialogId + '" class="video-upload-dialog"><br />' + Drupal.t('Loading...') + '</div>');

    // fetch the upload form from the server, attach the handlers, inject into the dialog
    $('#' + dialogId).load(Drupal.settings.basePath + 'video-upload/dialog/' + elementId + '/' + fieldName + '/' + typeName + '/' + nid, function(content) {
      $(this).html(content);

      // Initialize JQuery Form
      Drupal.videoUpload.attachDialogBehaviour(this);

      // Show the Upload button.
      var buttonContext = $(this).parent().parent()[0];
      $('.ui-dialog-buttonpane', buttonContext).show();
    });

    // everything is ready, launch the dialog.
    Drupal.videoUpload.initializeDialog(dialogId);

    return false;
  });
}

Drupal.videoUpload = function() {};

/**
 * A stack containing the field ids of widgets from which we launched dialogs.
 * This is needed because when an upload finishes, we don't actually know
 * which dialog finished (and we don't care), we just kill one, and fill one
 * empty space in the node add/edit form.
 *
 * This is done this way because we can't pass any params to the YouTube $nextUrl
 * and have them provided there (as a POST or GET param), which sucks.
 */
Drupal.videoUpload.fields = new Array();

/**
 * Initialize the JQuery UI Dialog.
 */
Drupal.videoUpload.initializeDialog = function(dialogId) {
  var buttons = {};
  var uploadLabel = Drupal.t("Upload");

  buttons[uploadLabel] = function() {
    $('form', this).submit();
  };

  $('#' + dialogId).dialog({
    title: Drupal.t('Upload a file to YouTube'),
    resizable: true,
    maximize: false,
    draggable: true,
    height: 190,
    width: 420,
    close: function(event, ui) {
      var dialogId = $(this).attr('id');
      var elementId = dialogId.replace('dialog-', '');
      var elementPos = jQuery.inArray(elementId, Drupal.videoUpload.fields);

      Drupal.videoUpload.fields.splice(elementPos, 1);
    },
    buttons: buttons
  });

  var buttonContext = $('#' + dialogId).parent().parent()[0];

  // Hide the Upload button (shown when the upload form loads)
  $('.ui-dialog-buttonpane', buttonContext).css('display', 'none');
}


/**
 * Initialize JQuery Form and attach it to the form in the dialog.
 */
Drupal.videoUpload.attachDialogBehaviour = function(context) {
  var elementId = $('#edit-element-id', context).attr('value');

  var options = {
    context: context,
    elementId: elementId,
    beforeSubmit:  Drupal.videoUpload.beforeSubmit,
    success:       Drupal.videoUpload.completeUpload
  };

  $('form', context).ajaxForm(options);
}

// JQuery Form presubmit handler
Drupal.videoUpload.beforeSubmit = function(formData, jqForm, options) {
  // Remove previous error message, if any
  $('.upload-validation-message', options.context).remove();

  var fileValue = $('input[type=file]', options.context).attr('value');

  if (fileValue == "") {
    var errorMessage = Drupal.t('No file selected.');
    $('#edit-upload-wrapper', options.context).append('<div class="upload-validation-message">' + errorMessage + '</div>');

    return false;
  }
  
  /**
  * Add client side validation for the input[type=file] accept attribute.
  */
  var accept = $('input[type=file]', options.context).attr('accept').replace(/,\s*/g, '|');

  if (accept.length > 1) {
    var v = new RegExp('\\.(' + accept + ')$', 'gi');
    
    if (!v.test(fileValue)) {
      var errorMessage = Drupal.t("The selected file cannot be uploaded. Extension not allowed.");
      
      $('#edit-upload-wrapper', options.context).append('<div class="upload-validation-message">' + errorMessage + '</div>');
      
      return false;
    }
  }
  
  // We passed validation, proceeding with the upload

  var buttonContext = $('#dialog-' + options.elementId).parent().parent()[0];
  var button = Drupal.t('Uploading...');

  /*
    For browsers that are not IE6/7 we insert a throbber.
    The throbber looks like crap on IE6/IE7, so we have to can't use it.
  */
  if(!$.browser.msie || $.browser.version > 7) {
    button = '<div class="ahah-progress ahah-progress-throbber">' +
               '<div class="throbber video-upload-throbber">&nbsp;</div>' +
              '</div>' + button;
  }

  $('button', buttonContext).html(button);

  return true;
}

/**
 * JQuery Form postsubmit handler.
 * Parses the response, closes the dialog, updates the widget on the
 * node add/edit page.
 */
Drupal.videoUpload.completeUpload = function(responseText) {
  var response = Drupal.parseJson(responseText);
  var elementId = Drupal.videoUpload.fields.shift();

  response.field = response.field.replace(/\$element\_id/g, elementId);

  $('#dialog-' + elementId).dialog('destroy');

  // remove the upload button, update the hidden fields
  $('#' + elementId + '-video-browser-upload').remove();
  $('#' + elementId + '-video-status').attr('value', 'unknown');
  $('#' + elementId + '-video-id').attr('value', response.id);

  if ($('#' + elementId + '-wrapper label', elementWrapper).length > 0) { // case when number of values in field is 1
    $('#' + elementId + '-wrapper label').after(response.field);
  } else { // case when number of values is more than 1
    $('#' + elementId + '-wrapper').prepend(response.field);
  }

  // reattach the js handler for the Remove button
  var elementWrapper = $('#' + elementId + '-wrapper')[0];
  Drupal.behaviors.videoUploadAttachDelete(elementWrapper);
}